package com.fowo.api.sys.performance.config;

import com.fowo.api.sys.performance.PerformanceLogService;
import com.fowo.api.sys.performance.aop.PerformanceLogInterceptor;
import com.fowo.api.sys.performance.properties.PerformanceLogProperties;
import org.springframework.aop.aspectj.AspectJExpressionPointcutAdvisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 性能日志自动配置类
 * @author yl_ls
 */
@Configuration
@ConditionalOnProperty("app.performance-log.writer")
public class PerformanceLogAutoConfig {

    public static final String DEFAULT_ANNOTATION_EXPRESSION = "@annotation(com.fowo.api.sys.performance.annotation.PerformanceLog)";

    @Resource
    private PerformanceLogProperties properties;

    @Resource
    private PerformanceLogService performanceLogService;

    @Bean
    public PerformanceLogInterceptor performanceLogInterceptor() {
        return new PerformanceLogInterceptor(performanceLogService);
    }


    @Bean
    public AspectJExpressionPointcutAdvisor performanceLogPointcutAdvisor() {
        AspectJExpressionPointcutAdvisor advisor = new AspectJExpressionPointcutAdvisor();
        if (StringUtils.hasText(properties.getAspectExpression())) {
            advisor.setExpression(DEFAULT_ANNOTATION_EXPRESSION + " || " + properties.getAspectExpression());
        } else {
            advisor.setExpression(DEFAULT_ANNOTATION_EXPRESSION);
        }
        advisor.setAdvice(performanceLogInterceptor());
        return advisor;
    }
}
